import asyncio
from fastapi import FastAPI, WebSocket
from fastapi.responses import HTMLResponse
from ai import get_ai_reply
from config import Config
from db import chat_col
import uvicorn

app = FastAPI()


@app.get("/", response_class=HTMLResponse)
async def home():
    """简单网页聊天界面"""
    return """
    <html>
    <body style='font-family:sans-serif;background:#f7f7f7;padding:20px;'>
        <h3>😂 AI 笑话聊天机器人</h3>
        <div id='chat' style='height:400px;overflow:auto;background:white;padding:10px;border-radius:8px;'></div>
        <input id='msg' placeholder='说点什么...' style='width:80%;' onkeydown="if(event.key==='Enter')send()">
        <script>
            const ws = new WebSocket('ws://'+location.host+'/ws');
            ws.onmessage = e => {
                document.getElementById('chat').innerHTML += '<p>🤖：'+e.data+'</p>';
            };
            function send(){
                let msg=document.getElementById('msg').value;
                ws.send(msg);
                document.getElementById('chat').innerHTML += '<p>🧑：'+msg+'</p>';
                document.getElementById('msg').value='';
            }
        </script>
    </body></html>
    """


@app.websocket("/ws")
async def ws_chat(ws: WebSocket):
    """聊天接口"""
    await ws.accept()
    # 主动问候，降低“你问我答”的单调感
    try:
        await ws.send_text("嗨～要不要听个冷笑话？你喜欢的主题是啥？")
    except Exception:
        pass
    try:
        while True:
            user_msg = await ws.receive_text()
            reply = await get_ai_reply(user_msg)
            # 将同步的 Mongo 写入放到线程池，避免阻塞
            await asyncio.get_running_loop().run_in_executor(
                None, chat_col.insert_one, {"user": user_msg, "bot": reply}
            )
            await ws.send_text(reply)
    except Exception:
        # 连接断开或其他异常时安全退出
        pass

if __name__ == "__main__":
    uvicorn.run(app, host=Config.SERVER_HOST, port=Config.SERVER_PORT)
